package com.cloud.service.impl;

import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.Message;
import com.cloud.factory.ServiceFactory;
import com.cloud.factory.ServiceInterface;
import com.cloud.service.CanalDataHandlerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@Slf4j
public class CanalDataHandlerServiceImpl implements CanalDataHandlerService {

    @Override
    public void handleMessage(Message message, CanalConnector connector) {
        //获取批量ID
        long batchId = message.getId();
        //获取批量的数量
        int size = message.getEntries().size();
        //如果没有数据
        if (batchId != -1 && size != 0) {
            // 发布任务  插入表数据，出现异常，插入一场表，等待定时处理或者人工处理
            handlerData(message.getEntries());
            // 进行 batch id 的确认。确认之后，小于等于此 batchId 的 Message 都会被确认。
            connector.ack(batchId);
        }
    }

    public void handlerData(List<CanalEntry.Entry> entrys) {
        for (CanalEntry.Entry entry : entrys) {
            if (CanalEntry.EntryType.TRANSACTIONBEGIN == entry.getEntryType() || CanalEntry.EntryType.TRANSACTIONEND == entry.getEntryType()) {
                //事务的实体类型，跳过
                continue;
            }
            //RowChange对象，包含了一行数据变化的所有特征
            //比如isDdl 是否是ddl变更操作 sql 具体的ddl sql beforeColumns afterColumns 变更前后的数据字段等等
            CanalEntry.RowChange rowChage;
            try {
                rowChage = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(), e);
            }

            //获取操作类型：insert/update/delete类型
            CanalEntry.EventType eventType = rowChage.getEventType();

            //获取RowChange对象里的每一行数据，打印出来
            for (CanalEntry.RowData rowData : rowChage.getRowDatasList()) {
                //如果是删除语句
                if (CanalEntry.EventType.DELETE == eventType) {
                    String result = printColumn(entry.getHeader(), rowData.getBeforeColumnsList(), eventType);
                    log.info("删除时 ：：：" + result);
                    buildDeleteExecute(entry.getHeader(), rowData.getBeforeColumnsList());
                } else if (CanalEntry.EventType.INSERT == eventType) {
                    String result = printColumn(entry.getHeader(), rowData.getAfterColumnsList(), eventType);
                    log.info("插入时 ：：：" + result);
                    buildInsertAndExecute(entry.getHeader(), rowData.getAfterColumnsList());
                    //如果是新增的语句
                } else if (CanalEntry.EventType.UPDATE == eventType) {
                    //如果是更新的语句
                    //变更前的数据
                    String before = printColumn(entry.getHeader(), rowData.getBeforeColumnsList(), eventType);
                    log.info("更新前 ：：：" + before);
                    //变更后的数据
                    String after = printColumn(entry.getHeader(), rowData.getAfterColumnsList(), eventType);
                    log.info("更新后 ：：：" + after);
                    buildUpdateAndExecute(entry.getHeader(), rowData.getAfterColumnsList());
                }
            }
        }
    }


    private void buildInsertAndExecute(CanalEntry.Header header, List<CanalEntry.Column> columns) {
        ServiceInterface obj = ServiceFactory.getService("mes$" + header.getTableName());
        if (obj == null) {
            return;
        }
        obj.execute(columns, "insert", header.getTableName());
    }

    private void buildUpdateAndExecute(CanalEntry.Header header, List<CanalEntry.Column> columns) {
        ServiceInterface obj = ServiceFactory.getService("mes$" + header.getTableName());
        if (obj == null) {
            return;
        }
        obj.execute(columns, "update", header.getTableName());

    }

    private void buildDeleteExecute(CanalEntry.Header header, List<CanalEntry.Column> columns) {
        ServiceInterface obj = ServiceFactory.getService("mes$" + header.getTableName());
        if (obj == null) {
            return;
        }
        obj.execute(columns, "delete", header.getTableName());
    }

    public String printColumn(CanalEntry.Header header, List<CanalEntry.Column> columns, CanalEntry.EventType eventType) {
        String result = "表名:" + header.getTableName() + ", 类型:" + eventType + ", 属性:";
        String columnString = "";
        for (CanalEntry.Column column : columns) {
            columnString += column.getName() + " : " + column.getValue() + ", ";
        }
        return result + columnString;
    }
}
